import React, {
	Component
}
from 'react';
import {
	render
}
from 'react-dom';
import {
	Spin, Table, Button, message, Row, Col, Modal, Icon
}
from 'antd';

var BookObj = Bmob.Object.extend("books");

var stopSeconds = (18 * 60 + 59) * 60 + 59;

function getDay() {
	var today = new Date();
	var dayTag = "" + today.getFullYear() + today.getMonth() + today.getDate();
	return dayTag;
}

function postData(data) {

	var arr = [];
	for(var i=0; i<data.length; i++){
		arr[i] = {};
		arr[i]['name'] = data[i]._serverData.username;
		arr[i]['dishes'] = data[i]._serverData.dishes;
	}
	
	/*
	$.get('/getData', {data: arr}, function(res) {
		console.log(res)
	})
	*/
}

class OperateBtn extends Component {
	constructor(props) {
		super(props);
		this.state = {};
	}
	delRecord() {
		var day = new Date();
		var overplus = stopSeconds - (day.getHours() * 60 + day.getMinutes()) * 60 + day.getSeconds();
		if (overplus <= 0) {
			message.error('已统计订餐情况，不能再修改');
			return
		}
		if (this.props.record.attributes.confirmkey != commonFingerPrint.get()) {
			message.warn('我猜不是你订的餐');
		} else {
			var queryDel = new Bmob.Query(BookObj);
			console.log(this.props.record.id)
			queryDel.get(this.props.record.id, {
				success: function(object) {
					object.destroy({
						success: function(myObject) {
							message.success('删除成功！')
							location.reload();
						},
						error: function(myObject, error) {
							message.error('删除失败，再来下');
						}
					})
				},
				error: function(object, error) {
					message.error('删除失败，再来下');
				}
			});
		}
	}
	render() {
		if(this.props.disabled){
			return <div />
		}

		return (
			<span>
				<Button type="primary" onClick={this.delRecord.bind(this)}>
				删除
				</Button>
			</span>
		)
	}
}

var BookList = React.createClass({
	getInitialState: function() {
		return {
			init: true,
			data: []
		};
	},

	componentDidMount: function() {

		var query = new Bmob.Query(BookObj);
		var context = this;
		query.limit(1000);
		query.equalTo("bookday", getDay());
		query.find({
			success: function(results) {
				context.setState({
					init: false,
					data: results
				});
				
				postData(results)
			},
			error: function(error) {
				alert("查询失败: " + error.code + " " + error.message);
			}
		});

		$(window).on('openBookModal', function(e){
			context.showBookModal();
		})
	},
	showBookModal(){
		this.setState({
			showBookModal: true
		})
	},
	handleOk(){
		this.setState({
			showBookModal: false
		})
	},
	handleCancel(){
		this.setState({
			showBookModal: false
		})
	},
	getTotal() {
		var data = this.state.data,
			nums = 0,
			prices = 0;

		if (!data.length) return;

		data.map(function(record) {

			if (!record.attributes) return;
			let names = record.attributes.dishes;
			let price = record.attributes.money;

			nums += names.length;

			prices += price;
		});

		return {
			nums: nums,
			prices: prices
		}
	},
	render: function() {
		let _this = this;

		if (this.state.init) {
			return (
				<div style={{padding: '6em 0 6em', textAlign: 'center'}}>
					<Spin />
				</div>
			)
		} else {
			let columns = [{
				title: '姓名',
				dataIndex: 'username',
				key: 'username',
				render: function(text, record, index) {
					if (index == listArr.length - 1) {
						return {
							children: <span>总计</span>
						}
					}

					return <span>{record.attributes.username||''}</span>
				}
			}, {
				title: '美食',
				dataIndex: 'dishes',
				key: 'dishes',
				render: function(text, record, index) {
					if (index == listArr.length - 1) {
						return {
							children: <span><em className="td-num">{record.nums}</em>份</span>
						}
					}
					var val = record.attributes.dishes.join(',');
					return <span>
						{val}
					</span>
				}
			}, {
				title: '价格/元',
				dataIndex: 'money',
				key: 'money',
				render: function(text, record, index) {
					if (index == listArr.length - 1) {
						return {
							children: <span><em className="td-num">{record.prices}</em>元</span>
						}
					}
					return <span>{record.attributes.money}</span>
				}
			}, {
				title: '操作',
				dataIndex: 'operate',
				key: 'operate',
				render: function(text, record, index) {
					if (index == listArr.length - 1) {
						return {
							children: <span></span>,
							colSpan: 0
						}
					}

					var disabled = record.attributes.confirmkey == commonFingerPrint.get() ? false : true;

					return (
						<span>
							<OperateBtn disabled={disabled} record={record} />
						</span>
					)
				}
			}];

			const listArr = this.state.data.concat();

			listArr.push(this.getTotal());

			const rowKey = function(record, index) {
				return index;
			}

			let orders = {};

			if(this.state.showBookModal){
				let data = this.state.data;

				data.map(function(record){
					if(!record.attributes) return;

					let names = record.attributes.dishes;

					names.map(function(name){
						if(orders[name]){
							orders[name]++;
						}else{
							orders[name] = 1;
						}
					})
				})
			}

			return (
				<div>
					<Table rowKey={rowKey} columns={columns} dataSource={listArr} pagination={false} bordered/>
					<Modal visible={this.state.showBookModal}
						title="订单汇总"
						onOk={this.handleOk}
						onCancel={this.handleCancel}>
						<TotalOrder orders={orders}/>
					</Modal>
				</div>
			);
		}
	}
});

class TotalOrder extends Component{
	render(){
		let arr = [], columns = [], orders = this.props.orders;

		for(var name in orders){
			arr.push({
				name: name,
				num: orders[name]
			})
		}

		columns = [{
			title: '菜名',
			dataIndex: 'name',
			key: 'name',
			sorter: function(prev, next){
				return prev.name < next.name
			}
		}, {
			title: '数量/份',
			dataIndex: 'num',
			key: 'num'
		}, {
			title: '店家',
			dataIndex: 'store',
			key: 'store'
		}];

		return (
			<div>
				<Table  className="mini-table" columns={columns}dataSource={arr} pagination={false} bordered/>
			</div>
		)
	}
}


class ListPage extends Component {
	constructor(props){
		super(props);

		this.state = {};

		//this.bind();
	}
	openModal(){
		$(window).trigger('openBookModal')
	}
	render() {
		return (
			<div id="listPage">
				<Row style={{background: '#eee url(/listimg) no-repeat center', backgroundSize: 'cover', height: '400px'}} className="index-banner">
					<Col span="20" offset="2">
					    <div className="jumbotron">
					        <h1>订餐列表</h1>
					        <p>想修改订餐可删除后再订餐；</p>
					    </div>
				    </Col>
				    <span className="book-btn-wrap">
					    <Button shape="circle-outline" className="book-btn" onClick={this.openModal.bind(this)}>
					    	<Icon type="book" />
					    </Button>
				    </span>
				    
				</Row>
				<Row>
					<Col span="20" offset="2">
						<BookList />
					</Col>
				</Row>
			</div>
		)
	}
}

export {
	ListPage
}